package org.btik.light.mobile.common.handler.adaptor;

import android.annotation.SuppressLint;
import android.view.MotionEvent;
import android.view.View;
import org.btik.light.mobile.common.handler.DevBinder;
import org.btik.light.mobile.meta.mo.DefaultDevMo;

import java.util.function.Consumer;

/**
 * 持续性按下事件，有两个事件 按下触发，松手结束
 * {@link #down} 按下的事件回调，如左转弯
 * {@link #up} 释放按钮时，回调左右差速状态解除，停止左转弯。
 * 或者麦克纳姆轮小车的漂移移动都需要松手停止
 */
public class TurnEventHandler implements View.OnTouchListener, DevBinder {
    // 开始转向
    private final Consumer<View> down;
    // 结束转向状态
    private final Consumer<View> up;

    public TurnEventHandler(Consumer<View> down, Consumer<View> up) {
        this.down = down;
        this.up = up;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                down.accept(v);
                break;
            case MotionEvent.ACTION_UP:
                up.accept(v);
                break;
        }
        return false;
    }

    @Override
    public void bind(DefaultDevMo devMo) {
        if (down instanceof DevBinder) {
            ((DevBinder) down).bind(devMo);
        }
        if (up instanceof DevBinder) {
            ((DevBinder) up).bind(devMo);
        }
    }
}
